<template>
  <el-config-provider>
    <router-view v-if="ready" />
  </el-config-provider>
</template>

<script setup lang="ts">
import { usePageVisibility } from '@/utils/usePageVisibility.ts';
import { setUser } from '@/utils/user.ts';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
const { proxy } = getCurrentInstance() as any;
const router = useRouter()
const ready = ref(false) // 替换 show 更具语义化
const { isVisible } = usePageVisibility();
// 监听可见性变化
watch(isVisible, (newVal) => {
  const startTime = proxy.$getItem('startTime');
  const time = proxy.$getMinutesDifference(startTime, new Date())
  if (time > 20) {
    const apiToken = localStorage.getItem('apiToken');
    if (apiToken) {
      proxy.$api.SystemManage.GetNewAuthenticationToken()
        .then((res: any) => {
          proxy.$setItem('authenticationToken', res.authenticationToken);
          proxy.$setItem('startTime', new Date());
        })
        .catch((err: any) => {
          console.error('更新心跳接口报错:', err)
        });
    }
  }
});
// 获取用户信息
const getUserComInfo = async () => {
  const apiToken = localStorage.getItem('apiToken') // 假设 $getItem 是对 localStorage 的封装
  if (!apiToken) {
    goLogin()
    return
  }
  proxy.$api.SystemManage.GetLoginedOperatorData()
    .then((res: any) => {
      setUser(res)
      ready.value = true
    })
    .catch((err: any) => {
      goLogin()
    });
}
const goLogin = () => {
  router.push('/login')
  ready.value = true
}
onMounted(() => {
  getUserComInfo()
})
</script>

<style scoped></style>